import _ from "lodash";
import React from "react";
import { toJS } from "mobx";
import { Spin, Modal, Pagination } from "antd";
import AppCard from "./card";
import { findDOMNode } from "react-dom";
import { WeaNewScroll, WeaLocaleProvider } from "ecCom";
import { inject, observer } from "mobx-react";
import { fillinTypes, actions } from "../../constants/app";
import _action from "../../apis/app";
const { EDIT, SETTING, DATA, TASK, SHARE, DELETE, COPY } = actions;
const getLabel = WeaLocaleProvider.getLabel;

@inject('edcAppStore')
@observer
export default class AppList extends React.Component {
  constructor(props) {
    super();
    this.store = props.edcAppStore;
    this.calcWidthForResize = _.debounce(this.calcWidth.bind(this), 300);
    this.state = {
      width: '100%'
    };
  }
  componentDidMount() {
    this.calcWidth();
  }

  calcWidth() {
    const CARD_MIN_WIDTH = 336;
    const CARD_MARGIN = 5;
    const CONTAINER_PADDING = 4 * 2;
    const containerDOM = findDOMNode(this.container);
    const parentDOM = containerDOM.parentNode;
    const num = parseInt((parentDOM.offsetWidth - CONTAINER_PADDING) / CARD_MIN_WIDTH);
    const restWidth = parentDOM.offsetWidth - CARD_MIN_WIDTH * num;
    const width = CARD_MIN_WIDTH + restWidth / num - CARD_MARGIN;

    this.setState({ width });
  }

  handleAction(action, app) {
    if (action === EDIT) {
      this.store.showEditDialog(app);
    } else if (action === SETTING) {
      this.store.showDesigner(app);
    } else if (action === DATA) {
      this.store.showData(app);
    } else if (action === TASK) {
      if (app.fillinType === fillinTypes.FREE) {
        this.store.showPublishDialog(app)
      } else {

        this.store.getAppPathid(app);
      }
    } else if (action === SHARE) {
      this.store.showShareDialog(app);
    } else if (action === DELETE) {
      Modal.confirm({
        title: getLabel('511886', '删除应用'),
        content: <span>{getLabel('511896', '确认删除应用吗?')}</span>,
        onOk: () => {
          this.store.deleteSingle(app);
        }
      });
    } else if (action === COPY) {
      const { displayType } = app
      _action.checkCreateMaxNum().then(result => {
        const { right, createtype: createType } = result;
        if (right === '1') {
          if (createType.indexOf(displayType) > -1) {
            this.store.openCopyAppDialog(app);
          } else {
            Modal.error({
              title: '另存为',
              content: <span style={{color:'red'}}>你所创建的{displayType}应用已达到上限,无法再复制，请联系管理员！</span>,
            });
          }
        } else {
          Modal.error({
            title: '另存为',
            content: <span style={{color:'red'}}>你所创建的应用已达到上限,无法再复制，请联系管理员！</span>,
          });
        }
      });



    }
  }

  getApps() {
    const { searchText, selectedType, apps, notMine } = this.store;
    const text = searchText.toLowerCase();

    return toJS(apps).filter(app => {
      const isMatchType = selectedType === fillinTypes.ALL || selectedType === app.fillinType;
      const isMatchText = ~app.name.toLowerCase().indexOf(text);

      return isMatchText && isMatchType;
    });
  }

  renderCards() {
    const { width } = this.state;
    const apps = this.getApps();
    const { onCheck, notMine } = this.store;

    return apps.map(app => (
      <AppCard ecId={`${this && this.props && this.props.ecId || ''}_AppCard@py4090@${app.uuid}`}
        key={app.uuid}
        style={{ width }}
        app={app}
        notMine={notMine}
        onActionClick={this.handleAction.bind(this)}
        onCheck={onCheck}
        checked={this.store.appids.indexOf(app.id) > -1}
      />
    ));
  }

  render() {
    const { spinning, current, total, changePage, changePageSize } = this.store;
    return (
      <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@aurvhu`} spinning={spinning} >
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@83xfl7`} style={{ position: "absolute", bottom: '50px', top: '0px', right: '0px', left: '0px' }}>
          <div ref={container => this.container = container} style={{ padding: '6px 4px 0px', margin: '0 auto' }}> {/** 修复滚动条无法覆盖底部应用问题 */}
            {this.renderCards()}
          </div>
        </WeaNewScroll>
        <div className="paginationDiv">
          <Pagination ecId={`${this && this.props && this.props.ecId || ''}_Pagination@c9lnl4`}
            total={total}
            showTotal={total => `${getLabel('18609', '共')} ${total} ${getLabel('18256', '条')}`}
            current={current}
            onChange={changePage}
            showSizeChanger
            defaultPageSize={20}
            pageSizeOptions={['20', '50', '100']}
            onShowSizeChange={changePageSize}
            showQuickJumper
            defaultCurrent={1}
          />
        </div>
      </Spin>
    );
  }
}